/**
 * CopyRight(C) HNA eKing Tech co,.cl
 * @Author ke_wan
 * @date 2013-9-5
 */
package com.hnas.sys.web.system;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hnas.core.dto.BaseAjaxResponse;
import com.hnas.core.dto.DTOPagedList;
import com.hnas.core.dto.DataBean;
import com.hnas.sys.core.util.UserUtils;
import com.hnas.sys.service.system.AuthorityService;
import com.hnas.sys.service.system.IManagerService;
import com.hnas.sys.service.system.UserService;
import com.hnas.sys.service.system.criteria.DTOSearchManager;
import com.hnas.sys.service.system.dto.DTOAuthority;
import com.hnas.sys.service.system.dto.DTOManager;
import com.hnas.sys.service.system.dto.DTOUser;

/**
 * <pre>用户后台管理控制器--添加后台用户</pre>
 * @author 许亚明(yam-xu)
 *
 */
@Controller
@RequestMapping("/backend/system/userManager")
public class UserManageController {
	private Logger log = LoggerFactory.getLogger(UserManageController.class);
	@Autowired
	private UserService userService;
	@Autowired
	private IManagerService managerService;
	@Autowired
	private AuthorityService authorityService;
	
	/**
	 * 
	 * <pre>用户维护初期化界面</pre>
	 * @Author 许亚明(yam-xu)
	 * @date 2013-9-12
	 * @param modelMap
	 * @return
	 */
//	@RequestMapping("/gotoUserManager")
//	public String gotoUserMaintain(ModelMap modelMap){
////		List<DTOUser> users = userService.getUserWithManagerRole("");
//		List<DTOAuthority> roleLists = authorityService.getAllAuthorities();
////		modelMap.put("users", users);
//		modelMap.put("roleLists", roleLists);
//		return "backend/system/userManager";
//	}
	
	@RequestMapping("/search")
	public String search(ModelMap modelMap, HttpServletRequest request,
			@ModelAttribute("criteria") DTOSearchManager criteria) {

		try {
//			String page = request.getParameter((new ParamEncoder("values")
//					.encodeParameterName(TableTagParameters.PARAMETER_PAGE)));
//			/**
//			 * if (!"false".equals(request.getParameter("firstInvoke"))) {
//			 * modelMap.put("resultSize", 0); return
//			 * "backend/product/searchProviders"; }
//			 **/
//			if (null == page) {
//				criteria.setPageNo(1);
//			} else {
//				criteria.setPageNo(Integer.parseInt(page));
//			}
			criteria.setTotalCount(-1);
//			DTOUser user = UserUtils.getCurrentUser();

			DTOPagedList<DTOManager> pg = this.managerService.search(criteria);
//			modelMap.put("citys", pg.getList());
			modelMap.put("pg", pg);
			modelMap.put("resultSize", pg.getTotalCount());
			modelMap.put("dto", criteria);
		} catch (Exception e) {
			log.error("", e);
			modelMap.put("resultSize", 0);
		}
		modelMap.put("pageTitle", "管理员维护");
		List<DataBean> beans = new ArrayList<DataBean>();
		beans.add(new DataBean("name","name","姓名",false,125));
		beans.add(new DataBean("account","account","账号",false,125));
		beans.add(new DataBean("password","password","密码",true,125));
		beans.get(beans.size()-1).setDisplay(false);
		beans.add(new DataBean("email","email","email",true,125));
		beans.add(new DataBean("telephone","telephone","手机",true,125));
		beans.add(new DataBean("userRole","userRole","科目号授权",true,125));
		//beans.add(new DataBean("agency.agencyName","agencyName","旅行社",false,125));
//		beans.add(new DataBean("statusStr","状态"));
//		beans.add(new DataBean("priority","排序","int"));
		modelMap.put("beans", beans);
		List<DTOAuthority> roleLists = authorityService.getAllAuthorities();
//		modelMap.put("users", users);
		modelMap.put("roleLists", roleLists);
		return "backend/system/user/listUsers";
	}
	
	@RequestMapping(value = "show/{id}", method = RequestMethod.POST)
	@ResponseBody
	public DTOManager show(@PathVariable("id") Long id) {
		DTOManager dto = this.managerService.get(id);
		dto.setPassword("");
		return dto;
	}

	@RequestMapping(value = "disable/{id}", method = RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse disable(@PathVariable("id") Long id) {
		BaseAjaxResponse res = new BaseAjaxResponse();
		this.managerService.disable(id);
		res.setResult(1);
		return res;
	}
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse add( DTOManager dto) {
		BaseAjaxResponse res = new BaseAjaxResponse();
		DTOUser dtoUser=this.userService.getUserByAccount(dto.getAccount());
		if(null!=dtoUser&&dtoUser.getId()>0){
			res.setResult(0);
			res.setErrorMessage("用户帐号已存在!");
			return res;
		}
		return this.save(dto);
	}
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse save( DTOManager dto) {
		BaseAjaxResponse res = new BaseAjaxResponse();
		try {
			this.managerService.save(dto);
			res.setResult(1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			res.setErrorMessage(e.getMessage());
		}		
		return res;
	}
	@RequestMapping(value = "updatePass", method = RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse updatePass(String oldPass,String newPass) {
		BaseAjaxResponse res = new BaseAjaxResponse();
		try {
			DTOManager dto=new DTOManager();
			DTOUser user =UserUtils.getCurrentUser();
			if(null==user){
				res.setResult(0);
				res.setErrorMessage("登陆超时");
				return res;
			}
			String oldPassMd5 = new Md5PasswordEncoder().encodePassword(oldPass, user.getAccount());
			if(!oldPassMd5.equals(user.getPassword())){
				res.setResult(0);
				res.setErrorMessage("旧密码不正确");
				return res;
			}
			dto.setId(user.getId());
			dto.setPassword(newPass);
			this.managerService.savePass(dto);
			res.setResult(1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			res.setResult(0);
			res.setErrorMessage(e.getMessage());
		}		
		return res;
	}
	/**
	 * 
	 * <pre>查询</pre>
	 * @Author 许亚明(yam-xu)
	 * @date 2013-9-9 
	 * @param request
	 * @param model
	 * @return String
	 */
//	@RequestMapping(value="/search",method=RequestMethod.GET)
//	public String searchUserMaintain(HttpServletRequest request, HttpServletResponse response,
//			ModelMap modelMap){
//		//获取前台的数据
//		List<DTOAuthority> roleLists = authorityService.getAllAuthorities();
//		String searchAccount = request.getParameter("searchAccount");
//		List<DTOUser> users = userService.loadAll();//.getUserWithManagerRole(searchAccount);
//		
//		modelMap.put("users", users);
//		modelMap.put("roleLists", roleLists);
//		modelMap.put("searchAccount", searchAccount);
//		return "backend/system/userManager";
//	}
	
	/**
	 * 
	 * <pre>更新用户</pre>
	 * @Author 许亚明(yam-xu)
	 * @date 2013-9-9 
	 * @param user
	 * @param request
	 * @param response
	 * @return
	 */
//	@ResponseBody
//	@RequestMapping(value="search/add")
//	public String addUser(@ModelAttribute("user")DTOUser user,
//			HttpServletRequest request, HttpServletResponse response){
//
//		   String result = "fail";
//		   
//		   String roles = request.getParameter("roles");
//		   String [] roleArray = this.stringToArray(roles);
//		   List<DTOAuthority> list = new ArrayList<DTOAuthority>();
//		   // 添加角色
//		   if (roleArray != null && roleArray.length > 0) {
//			   DTOAuthority dtoAuthority = null;
//			   for (int i=0; i < roleArray.length; i++) {
//				   dtoAuthority = new DTOAuthority();
//				   dtoAuthority.setId(Long.valueOf(roleArray[i]));
//				   list.add(dtoAuthority);
//			   }
//			   user.setDtoAuthorities(list);
//		   }
//		   
//	       
//		  
//		   if (user != null) {
//			   DTOUser dtoUser = userService.getUserByAccount(user.getAccount());
//			   // 添加的场合
//			   if (user.getId() == null|| user.getId()==0) {
//				    // 账户存在
//				    if (dtoUser != null) {
//				    	result += ":登陆账户已存在！";
////				    	doAjaxResponse(response, result);
//				    	return result;
//				    }
//			   }
//			   else { 
//				   // 修改的场合 修改后的账户已经存在
//				   DTOUser dtoOrigin = userService.getUserById(user.getId());
//				   if (dtoOrigin != null
//						   && !StringUtils.equals(user.getAccount(), dtoOrigin.getAccount())) {
//					    // 账户存在
//					    if (dtoUser != null) {
//					    	result += ":登陆账户已存在！";
////					    	doAjaxResponse(response, result);
//					    	return result;
//					    }
//				   }
//			   }
//		   }
//		  
//	       try{
////	    	   if (UserUtils.getCurrentUser() != null) {
////	    		   user.setOperator(UserUtils.getCurrentUser().getId());
////	    	   }
////	    	   user.setOperateTime(DateUtil.dateToString(new Date()));
//			   if (user != null && user.getId() != null && user.getId()!=0) {
//				   // 保存用户修改信息
//				   DTOUser moidfyUser = userService.getUserById(user.getId());
//				   moidfyUser.setAccount(user.getAccount());
//				   moidfyUser.setName(user.getName());
////				   moidfyUser.setCompany(user.getCompany());
//				   moidfyUser.setTelephone(user.getTelephone());
//				   moidfyUser.setEmail(user.getEmail());
//				   moidfyUser.setDtoAuthorities(user.getDtoAuthorities());
//				   userService.updateUser(moidfyUser);;
//			   }
//			   else {
//				   // 保存用户添加信
////				   user.setName(user.getName());
//				   user.setPassword("");
//				   user.setStatus(ManagerStatus.VALID);
////				   user.setTelephone(user.getTelephone());
////				   user.setEmail(user.getEmail());
////				   user.set
////				   user.setStatusStr("VALID");
//				   userService.add(user, 0);
//			   }
//	    	   result = "success";
//	       }catch(Exception e){
//	    	   //e.printStackTrace();
//	       }
////	       doAjaxResponse(response, result);
//		   return result;
//	}
	
	/**
	 * 
	 * <pre>根据id查询or查看</pre>
	 * @Author 许亚明(yam-xu)
	 * @date 2013-9-9
	 * @param id
	 * @param model
	 * @return
	 */
//	@RequestMapping(value="search/{id}",method=RequestMethod.GET)	
//	@ResponseBody
//	public Map loadUserMaintain(@PathVariable("id") Long id, ModelMap model) {
//		DTOUser dtoUser = userService.getUserById(id);
//		Map<String,Object> map = new HashMap<String,Object>();
//		map.put("dtoUser", dtoUser);
//		return map;
//		
//	}
	
	/**
	 * 
	 * <pre>删除</pre>
	 * @Author 许亚明(yam-xu)
	 * @date 2013-9-9 
	 * @param id
	 * @return
	 */
//	@RequestMapping(value="search/{id}",method=RequestMethod.DELETE)
//	@ResponseBody
//	public Object deleteUserMaintain(@PathVariable("id") Long id) {
//		String result = "success";
//		try {
//			userService.delete(id);
//		} catch (Exception e) {
//			result = "fail";
//		}
//		return result;
//	}

	
	/**
	 * 
	 * <pre>返回结果</pre>
	 * @Author 许亚明(yam-xu)
	 * @date 2013-9-9 下午03:38:26
	 * @param response
	 * @param result
	 */
//	public void doAjaxResponse(HttpServletResponse response, String result) {
//		try {
//			response.setContentType("text/html");
//			PrintWriter out = response.getWriter();
//			out.flush();
//			out.print(result);
//			out.flush();
//			out.close();
//		} catch (Exception e) {
//			//e.printStackTrace();
//		}
//	}
	
	/**
	 * <pre>
	 * 字符串转换成数组.
	 * </pre>
	 * @auther 许亚明（yam-xu）
	 * 2013-9-4
	 * @param str
	 * @return String[]
	 */
//	public String[] stringToArray(String str) {
//		if (StringUtil.isNotEmpty(str)) {
//			str = str.substring(0, str.length()-1);
//			String[] resultArray = str.split("/");
//			return resultArray;
//		}
//		return null;
//	}
}
